<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        main {
            width: 1200px;
            height: auto;
            margin: 0 auto;
        }

        .head {
            display: flex;
            justify-content: space-between;

        }

        .head .avatar, .mood-box {
            display: flex;
            justify-content: left;
            align-items: center;
        }

        .head .avatar img {
            width: 100px;
            height: 100px;
            margin-right: 10px;
            cursor: pointer;
        }

        .mood-box textarea {
            outline: 1px solid #cfcfcf;
            border: none;
            max-width: 300px;
            min-width: 100px;
            width: 200px;
            height: 40px;
            margin-right: 10px;
            text-indent: 5px;
            resize: none;
        }

        .mood-box button {
            width: 67px;
            height: 30px;
            background-color: #2196f3;
            border: 0;
            outline: 0;
            border-radius: 5px;
            color: #fff;
            cursor: pointer;
        }

        .wrapper {
            margin-top: 50px;
        }

        .wrapper nav {
            display: flex;
            justify-content: left;
            align-items: center;
        }

        .wrapper nav span {
            width: 82px;
            height: 30px;
            background-color: #fff;
            border-radius: 5px;
            color: #000;
            text-align: center;
            line-height: 30px;
            cursor: pointer;
        }

        .wrapper nav span.active {
            background-color: #3a8ee6;
            color: #fff;
        }

        .wrapper textarea {
            resize: none;
            width: 100%;
            height: 80px;
            border: 0;
            outline: 1px solid #cfcfcf;
            margin-top: 10px;
            padding: 4px;
            box-sizing: border-box;
        }

        .wrapper ul {
            list-style-type: none;

        }

        .wrapper ul li {
            display: flex;
            justify-content: space-between;
            align-items: center;
            text-align: right
        }
        .wrapper ul li {
            margin-top: 10px;
        }

        .wrapper ul li > div:first-child {
            width: 200px;
            display: flex;
            align-items: center;
        }

        .wrapper ul li > div:last-child {
            flex: 1;
            display: flex;
            flex-wrap: wrap;
            flex-direction: column;
            text-align: right;
        }

        .wrapper ul li > div:first-child img {
            width: 50px;
            height: 50px;
            margin-right: 10px;
        }

        .wrapper ul li > div:first-child div img {

        }

        .textarea {
            height: 60px;
            line-height: 20px;
            padding: 3px 8px 5px;
            background: none;
            font-size: 14px;
            box-shadow: inset 0 2px 4px 0 rgb(0 0 0 / 4%);

        }


        .textarea-parent.hidden, .blog-title.hidden {
            display: none !important;
        }
        .textarea-parent{
            position: relative;

        }
        .textarea-parent button{
            position: absolute;
            bottom: 0;
            right: 0;
        }
        .wrapper ul li .blog_details {
            cursor: pointer;
        }

        .blog-title {
            width: 100%;
            height: 40px;
            margin-top: 20px;
            border: 0;
            outline: 1px solid #cfcfcf;
            border-radius: 55px;
            display: block;
            text-indent: 5px;
        }
        .avatar-box div>span{
            text-align: left;
            display: block;
            font-size: 12px;
            padding: 2px;
            box-sizing: border-box;
            border-radius: 6px;
            color: #777;
        }
        .blog-content{
            flex: 1;
        }
        .blog-content p{
            margin:10px 0;
        }
        .blog-content>span{
            font-size: 12px;
            color: #777;
            font-weight: 200;
            font-family: "Microsoft Yahei"
        }
        .blog-content button{
            margin: 0 10px;
        }
    </style>
</head>
<body>
<div class="container">
    <main>
        <header class="head">
            <div class="avatar">
                <img src="./images/699pic_08j9y6_xy.jpg" alt="">
                <span>恋人心</span>
            </div>
            <div class="mood-box">
                <textarea type="text" name="content"></textarea>
                <button>发布心情</button>
            </div>
        </header>
        <div class="wrapper">
            <nav>
                <span class="speak active">发表说说</span>
                <span class="blog">发表博客</span>
            </nav>
            <input type="text" class="blog-title" name="blogname">
            <textarea name="input" placeholder="来比吃两句"></textarea>
            <ul>
                <li>
                    <div class="avatar-box">
                        <img src="./images/2017-07-28%20160459.png" alt="">
                        <div class=''>
                            <figure>恋人心</figure>
                            <span>博客</span>
                        </div>
                    </div>
                    <div class="blog-content">
                        <span>2010-02-03</span>
                        <p>阿斯顿发是打发斯蒂芬sad</p>
                        <div>
                            <button>点赞</button>
                            <span></span>
                            <button>评论</button>
                        </div>
                        <div class="textarea-parent hidden">
                            <div class="textarea " contenteditable="true">打的费</div>
                            <button onclick="publishSpeak(this)">发表</button>
                        </div>
                    </div>
                </li>
            </ul>
        </div>
    </main>
</div>
<script>

    // 获取dom
    function $(el) {
        return document.querySelector(el);
    }
    // 单点登录
    // function isLogin() {
    //     const coookie = document.cookie.split('=')[1]
    //     if ( !coookie ) {
    //        location.href = './login.html'
    //     }
    // }
    // isLogin()
    const uid = localStorage.getItem('uid')
    // 发布心情
    $(".mood-box button").addEventListener('click', () => {
        $('.mood-box');
        ajax({
            url: '/api/blog/publishMood',
            type: 'GET',
            data: {
                content: $('.mood-box textarea').value,
                uid
            },
            async: true,
            authorization: 'Bearer ' + localStorage.getItem('token'),
            success(result) {
                console.log(result);
                const {msg, status} = JSON.parse(result);
                if (!status) {
                    alert(msg)

                }
            }
        });
    });
    // 获取心情
    initMood();

    function initMood(params) {
        ajax({
            url: '/api/blog/newMood',
            type: 'GET',
            data: {uid},
            async: true,
            authorization: 'Bearer ' + localStorage.getItem('token'),
            success(result) {
                console.log(result)
                const {data: {content}} = JSON.parse(result)
                console.log('')
                $('.mood-box textarea').value = content
            }
        });
    }

    //  导航按钮
    $('nav').addEventListener('click', function ( {target} ) {
        if (target.tagName === 'SPAN') {
            // console.dir(target)
            // const active = target.getElementsByClassName('.active');
            // active.classList.remove('active')
            // target.classList.add('active')
            // console.log(active)
            // shuoshuo

            if (target.classList.contains('speak')) {
                if (!$('textarea[name=input]').value) {
                    alert('内容不能空')
                    return
                }
                $('.blog-title').classList.add('hidden')
                $('.blog-title').value = ''; // 标题清空,防止发表说说的时候带上标题
                publishBlogRequest({
                    content: $('textarea[name=input]').value,
                    uid
                });
            } else {
                // 博客
                if (!$('.blog-title').value) {
                    alert('标题不能为空')
                    return
                }
                $('.blog-title').classList.remove('hidden')
                publishBlogRequest({
                    title: $('.blog-title').value,
                    content: $('textarea[name=input]').value,
                    uid,
                });
            }
        }
    });
    initBlogList()

    // 获取 博客说说列表
    function initBlogList() {
        ajax({
            url: '/api/blog/blogList',
            type: 'POST',
            data: {uid},
            async: true,
            authorization: 'Bearer ' + localStorage.getItem('token'),
            success(result) {
                console.log('result', JSON.parse(result))
                const {data, status, msg} = JSON.parse(result)
                if (!status && data.length) {
                    renderHtml(data)
                } else {
                    nullData()
                }
            }
        })
    }
    // 发表博客
    function publishBlogRequest(option) {
        console.log(localStorage.getItem('token'))
        ajax({
            url: '/api/blog/publish',
            type: 'POST',
            data: option,
            async: true,
            authorization: 'Bearer ' + localStorage.getItem('token'),
            success(result) {
                console.log('result', result);
                initBlogList()
            }
        })
    }

    // 渲染博客列表
    function renderHtml(dataList) {
        let html = '';
        for (let i = 0; i < dataList.length; i++) {
            html += `<li>`
            html += `<div class="avatar-box">`
            html += `<img src=${dataList[i].userinfo.avatar} alt="">`
            html += `<div class=''>`
            html += `<figure>恋人心</figure>`
            if (dataList[i].blog_title) {
                html += `<span>博客</span>`
            } else {
                html += `<span>说说</span>`
            }
            html += `</div>`
            html += `</div>`
            html += `<div class="blog-content">`
            html += `<span>${transDate(dataList[i].publish_time)}</span>`
            if (dataList[i].blog_content) {
                html += `<p class="blog_details" data-details="${dataList[i].blog_content}">${dataList[i].blog_title}</p>`
            } else {
                html += `<p>${dataList[i].speak_content}</p>`
            }
            html += `<button class="like" data-id="${dataList[i].id}" data-uid="${dataList[i].uid}">点赞</button>`
            html += `<span class="count">${dataList[i].like_no}</span>`
            html += `<button class="txt" onclick="comment(this)">评论</button>`
            html += `</div>`
            html += `   <div class="textarea-parent hidden">`
            html += `   <div class="textarea" contenteditable="true">打的费</div>`
            html += `   <button data-id="${dataList[i].id}" onclick="publishMoment(this)">发表</button>`
            html += `   </div>`
            // html += `<div class="textarea hidden" contenteditable="true"></div>`
            html += `</div>`
            html += `</li>`
        }
        $('.wrapper ul').innerHTML = html;
    }
    // 跳转详情
    $('.wrapper ul').addEventListener('click', ( { target } ) => {
        if ( target.tagName === 'P' && target.classList.contains('blog_details'))  {
            console.log()
            const details = target.dataset['details'];
            alert(details)
            // const xhr = new XMLHttpRequest;
            // xhr.open('get',`/api/blog/details?id=${ id }`, true);
            // xhr.setRequestHeader('authorization','Bearer ' + localStorage.getItem('token'));
            // xhr.onload = function () {
            //     console.log(xhr.responseText)
            // }
            // xhr.send();
        } else if ( target.tagName == 'BUTTON') {
            // 点赞

            if ( target.classList.contains('like') && !target.classList.contains('active') ) {
                console.dir(target)
                target.nextSibling.innerHTML = parseInt( target.nextSibling.innerHTML == '' ? 0 : target.nextSibling.innerHTML )+  1
                sendLikeCount({
                    count: target.nextSibling.innerHTML,
                    id: target.dataset['id'],
                    uid: target.dataset['uid']
                })
                target.classList.add('active');
            } else {
            //    评论
            }
        }

    });
    // 点赞
    function sendLikeCount( option ) {
        ajax({
            url: '/api/blog/likeCount',
            type: 'GET',
            data: option,
            authorization: 'Bearer ' + localStorage.getItem('token'),
            async: true,
            success( result ) {
                console.log(result)
            }
        })
    }
    function comment( self ) {
        // console.dir(self)
        const last = self.parentElement.parentElement.children.length;
        self.parentElement.parentElement.children[last - 1].classList.remove('hidden')

    }
    function publishMoment( self ) {
        const last = self.parentElement;
        console.dir( self.previousElementSibling.innerHTML)
        const html = self.previousElementSibling.innerHTML;
        console.dir()
        const id = self.getAttribute('data-id')
        ajax({
            url: 'http://127.0.0.1:3000/api/blog/publishMoment',
            type: 'GET',
            data: {
                content: html,
                id
            },
            authorization: 'Bearer '+ localStorage.getItem('token'),
            success( result ) {
                console.log(result)
            }
        })
    }
    // 列表为空
    function nullData() {
        let html = ''
    }

    function ajax(options) {
        const params = formsParams(options.data)
        const xhr = new XMLHttpRequest;
        // 连接
        if (options.type == "GET") {
            xhr.open(options.type, options.url + "?" + params, options.async);
            console.log(options.authorization)
            options.authorization && xhr.setRequestHeader('authorization', options.authorization)
            xhr.send(null)
        } else if (options.type == "POST") {
            xhr.open(options.type, options.url, options.async);
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            options.authorization && xhr.setRequestHeader('authorization', options.authorization)
            xhr.send(params);
        }
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
                options.success(xhr.responseText);
            }
        }

        function formsParams(data) {
            var arr = [];
            for (var prop in data) {
                arr.push(prop + "=" + data[prop]);
            }
            return arr.join("&");
        }
    }

    function transDate(stamtime) {
        const date = new Date(stamtime);
        var YY = date.getFullYear();
        var MM = toDou(date.getMonth() + 1)
        var DD = toDou(date.getDate());
        var hh = toDou(date.getHours());
        var mm = toDou(date.getMinutes());
        var ss = toDou(date.getSeconds());
        return `${YY}-${MM}-${DD} ${hh}:${mm}:${ss}`
    }

    function toDou(n) {
        return n < 10 ? '0' + n : n;
    }
    function timeOut( delay  = 1000) {
        return new Promise(( resolve, reject)=> {
            setTimeout(resolve,delay)
        })
    }
    var name = 'lisi';
    (function(){
        if ( typeof name == undefined){
            var name = 'wangwu';
            console.log('hello',name)
        } else {
            console.log('laiba',name)
        }
    })()
</script>
</body>
</html>